import argparse
import traceback
from flask import request, jsonify
from flask_jwt_extended import jwt_required
from server_util import get_table_name_by_device, get_timestamp, get_table_name_by_secret_card
from server_auth import admin_page
from server_init import gate_info_cache, car_count_temp_file_path, pass_info_cache, load_data_to_cache, app

app.register_blueprint(admin_page)


@app.route('/all-gate-show-info', methods=['GET'])
@jwt_required(optional=False)
def all_gate_show_info():
    response = []
    for data in gate_info_cache.values():
        response.append([data.gate_id, data.gate_longitude, data.gate_latitude])
        # if len(response) >= 100:
        #     break
    return jsonify(response)


@app.route('/gates-by-ids', methods=['GET'])
@jwt_required(optional=False)
def gate_by_id():
    args = request.args
    if 'gate_ids' not in args:
        return 'gate_ids'

    gate_ids = args.get('gate_ids')
    gate_ids = gate_ids.split(',')
    print(gate_ids)

    response = []
    for gate_id in gate_ids:
        gate_info = gate_info_cache[gate_id]
        response.append(gate_info.to_array())
    return jsonify(response)


@app.route('/search/all-gates-by-name', methods=['GET'])
@jwt_required(optional=False)
def all_gate_by_name():
    args = request.args
    if 'gate_name' not in args:
        return '缺少参数gate_name'

    gate_name = args['gate_name']
    response = []
    for gate_info in gate_info_cache.values():
        if gate_name in gate_info.gate_name:
            response.append(gate_info.to_array())
    print('response is {}'.format(response))
    return jsonify(response)


@app.route('/search/gates-by-name', methods=['GET'])
@jwt_required(optional=False)
def gate_by_name():
    args = request.args
    if 'gate_name' not in args:
        return '缺少参数gate_name'
    if 'offset' not in args:
        return '缺少参数offset'
    if 'num' not in args:
        return '缺少参数num'

    gate_name = args['gate_name']
    offset = int(args['offset'])
    num = int(args['num'])

    response = []
    for gate_info in gate_info_cache.values():
        if gate_name in gate_info.gate_name:
            response.append(gate_info.to_array())
    print('response is {}'.format(response))
    return jsonify(response[offset:offset + num])


@app.route('/search/gate-name-options', methods=['GET'])
@jwt_required(optional=False)
def search_gate_name_options():
    args = request.args
    if 'gate_name' not in args:
        return '缺少参数gate_name'

    gate_name = request.args['gate_name']
    # sql = "SELECT gate_name FROM gate_info where gate_name like '%{}%' limit 10".format(gate_name)

    response = []
    for gate_info in gate_info_cache.values():
        if gate_name in gate_info.gate_name:
            response.append([gate_info.gate_name])
            if len(response) >= 10:
                break

    print('response is {}'.format(response))
    return jsonify(response)


@app.route('/search-page-gate', methods=['GET'])
@jwt_required(optional=False)
def search_page_gate():
    args = request.args
    if 'offset' not in args:
        return '缺少参数offset'
    if 'num' not in args:
        return '缺少参数num'

    offset = int(args['offset'])
    num = int(args['num'])

    response = []
    for gate_info in gate_info_cache.values():
        response.append(gate_info.to_array())
        if len(response) == offset + num:
            break

    return jsonify(response[offset:offset + num])


@app.route('/gate-by-road-name', methods=['GET'])
@jwt_required(optional=False)
def gate_by_road_name():
    args = request.args
    if 'road_name' not in args:
        return '缺少参数road_name'
    if 'offset' not in args:
        return '缺少参数offset'
    if 'num' not in args:
        return '缺少参数num'

    road_name = args['road_name']
    offset = int(args['offset'])
    num = int(args['num'])

    response = []
    for gate_info in gate_info_cache.values():
        if gate_info.road_name == road_name:
            response.append(gate_info.to_array())
        if len(response) == offset + num:
            break
    print('response is {}'.format(response))
    return jsonify(response[offset:offset + num])


@app.route('/all-gate-by-road-name', methods=['GET'])
@jwt_required(optional=False)
def all_gate_by_road_name():
    args = request.args
    if 'road_name' not in args:
        return '缺少参数road_name'

    road_name = args['road_name']

    response = []
    for gate_info in gate_info_cache.values():
        if gate_info.road_name == road_name:
            response.append(gate_info.to_array())

    print('response is {}'.format(response))
    return jsonify(response)


@app.route('/gate-count', methods=['GET'])
@jwt_required(optional=False)
def gate_count():
    return jsonify([len(gate_info_cache.keys())])


@app.route('/gate-count-by-name', methods=['GET'])
@jwt_required(optional=False)
def gate_count_by_name():
    args = request.args
    if 'gate_name' not in args:
        return '缺少参数gate_name'

    gate_name = args['gate_name']
    count = 0
    for gate_info in gate_info_cache.values():
        if gate_name in gate_info.gate_name:
            count += 1

    return jsonify([count])


@app.route('/gate-count-by-road', methods=['GET'])
@jwt_required(optional=False)
def gate_count_by_road():
    args = request.args
    if 'road_name' not in args:
        return '缺少参数road_name'

    road_name = args['road_name']
    count = 0
    for gate_info in gate_info_cache.values():
        if gate_info.road_name == road_name:
            count += 1

    return jsonify([count])


@app.route('/car-count-by-time', methods=['GET'])
@jwt_required(optional=False)
def car_count_by_time():
    args = request.args
    if 'gate_id' not in args:
        return '缺少参数gate_id'
    if 'start_time' not in args:
        return '缺少参数start_time'
    if 'end_time' not in args:
        return '缺少参数end_time'

    gate_id = args['gate_id']
    start_time = args['start_time']
    end_time = args['end_time']

    table_index = get_table_name_by_device(gate_id)
    print('table_index is {}'.format(table_index))
    if table_index == -1:
        return jsonify([0])

    filename = 'gate_pass_info_device/gate_pass_info_device_{}'.format(table_index)
    # result = [['设备号', '卡口编号', '车辆属性', '车牌属性', '过车时间戳', '归属地', '车牌尾号', '加密后的车牌\n']]
    result = ['设备号, 卡口编号, 车辆属性, 车牌属性, 过车时间戳, 归属地, 车牌尾号, 加密后的车牌\n']
    with open(filename, 'r', encoding='utf8') as f:
        for line in f:
            line_split = line.split(',')
            timestamp = get_timestamp(line_split[4])
            if line_split[0] == gate_id and int(start_time) <= timestamp <= int(end_time):
                # result.append([line_split[0], line_split[1], line_split[2], line_split[3], line_split[4], line_split[5], line_split[6], line_split[7]])
                result.append(line)

    # 构造文件路径名
    filepath = 'static/{}-{}-{}.csv'.format(gate_id, start_time, end_time)
    # filepath = 'static/car-info-by-time-result.csv'
    print('filepath is {}'.format(filepath))

    with open(filepath, 'w', encoding='gbk') as f:
        for line in result:
            # line = ','.join(data)
            f.write(line)
    print('car-count-by-time count is {}'.format(len(result) - 1))
    return jsonify([len(result) - 1])


@app.route('/card', methods=['GET'])
@jwt_required(optional=False)
def card():
    args = request.args
    if 'secret_card' not in args:
        return '缺少参数secret_card'

    secret_card = args['secret_card']
    table_index = get_table_name_by_secret_card(secret_card)
    if table_index == -1:
        return jsonify([])

    temp_response = set()
    table_name = 'gate_pass_info_{}'.format(table_index)
    with open('gate_pass_info/{}'.format(table_name), 'r', encoding='utf8') as f:
        for line in f:
            line = line.replace('\n', '')
            line_split = line.split(',')
            file_secret_card = line_split[-1]
            if file_secret_card == secret_card:
                temp_response.add('{},{},{}'.format(line_split[-3], line_split[-2], line_split[-1]))
                break

    print(temp_response)
    response = []
    for r in temp_response:
        response.append(r.split(','))
    print('response is {}'.format(response))
    return jsonify(response)


@app.route('/card-detail', methods=['GET'])
@jwt_required(optional=False)
def card_detail():
    args = request.args
    # if 'location' not in args:
    #     return '缺少参数location'
    # if 'tail' not in args:
    #     return '缺少参数tail'
    if 'secret_card' not in args:
        return '缺少参数secret_card'

    location = args['location']
    tail = args['tail']
    secret_card = args['secret_card']
    table_index = get_table_name_by_secret_card(secret_card)
    if table_index == -1:
        return jsonify([])

    response = []
    table_name = 'gate_pass_info_{}'.format(table_index)
    with open('gate_pass_info/{}'.format(table_name), 'r', encoding='utf8') as f:
        for line in f:
            line = line.replace('\n', '')
            line_split = line.split(',')
            file_location = line_split[-3]
            file_tail = line_split[-2]
            file_secret_card = line_split[-1]
            # if file_secret_card == secret_card and file_location == location and file_tail == tail:
            if file_secret_card == secret_card:
                response = line_split
                break

    return jsonify(response)


@app.route('/pass-count', methods=['GET'])
@jwt_required(optional=False)
def pass_count():
    args = request.args
    if 'secret_card' not in args:
        return '缺少参数secret_card'
    if 'start_time' not in args:
        return '缺少参数start_time'
    if 'end_time' not in args:
        return '缺少参数end_time'

    secret_card = args['secret_card']
    start_time = int(args['start_time'])
    end_time = int(args['end_time'])

    table_index = get_table_name_by_secret_card(secret_card)
    if table_index == -1:
        return [0]

    table_name = 'gate_pass_info_{}'.format(table_index)
    count = 0
    with open('gate_pass_info/{}'.format(table_name), 'r', encoding='utf8') as f:
        for line in f:
            line = line.replace('\n', '')
            line_split = line.split(',')
            timestamp = get_timestamp(line_split[4])
            if start_time <= timestamp <= end_time and secret_card == line_split[len(line_split) - 1]:
                count += 1

    return jsonify([count])


@app.route('/pass-info', methods=['GET'])
@jwt_required(optional=False)
def pass_info():
    args = request.args
    if 'secret_card' not in args:
        return '缺少参数secret_card'
    if 'start_time' not in args:
        return '缺少参数start_time'
    if 'end_time' not in args:
        return '缺少参数end_time'
    if 'offset' not in args:
        return '缺少参数offset'
    if 'num' not in args:
        return '缺少参数num'

    secret_card = args['secret_card']
    start_time = int(args['start_time'])
    end_time = int(args['end_time'])
    offset = int(args['offset'])
    num = int(args['num'])

    if secret_card in pass_info_cache:
        return jsonify(pass_info_cache[secret_card][offset:offset + num])

    table_index = get_table_name_by_secret_card(secret_card)
    if table_index == -1:
        return []

    table_name = 'gate_pass_info_{}'.format(table_index)
    response = []
    with open('gate_pass_info/{}'.format(table_name), 'r', encoding='utf8') as f:
        for line in f:
            line = line.replace('\n', '')
            line_split = line.split(',')
            timestamp = get_timestamp(line_split[4])
            if start_time <= timestamp <= end_time and secret_card == line_split[len(line_split) - 1]:
                device = line_split[0]
                if device not in gate_info_cache:
                    continue
                gate_info = gate_info_cache[device]
                gate_info_array = gate_info.to_array()
                # 保持sql查询结果的格式
                gate_info_array.append(device)
                gate_info_array.append(timestamp)
                response.append(gate_info_array)

    response.sort(key=lambda e: e[-1])
    pass_info_cache[secret_card] = response
    return jsonify(response[offset:offset + num])


@app.route('/car-pass-info', methods=['GET'])
def car_pass_info():
    args = request.args
    if 'secret_card' not in args:
        return '缺少参数secret_card'
    if 'location' not in args:
        return '缺少参数location'
    if 'tail' not in args:
        return '缺少参数tail'
    if 'start_time' not in args:
        return '缺少参数start_time'
    if 'end_time' not in args:
        return '缺少参数end_time'

    secret_card = args['secret_card']
    start_time = int(args['start_time'])
    end_time = int(args['end_time'])
    location = args['location']
    tail = args['tail']

    table_index = get_table_name_by_secret_card(secret_card)
    if table_index == -1:
        return []

    table_name = 'gate_pass_info_{}'.format(table_index)
    response = []
    with open('gate_pass_info/{}'.format(table_name), 'r', encoding='utf8') as f:
        for line in f:
            try:
                line = line.replace('\n', '')
                line_split = line.split(',')

                line_timestamp = get_timestamp(line_split[4])
                line_secret_card = line_split[len(line_split) - 1]
                line_location = line_split[5]
                line_tail = line_split[6]
                if start_time <= line_timestamp <= end_time and secret_card == line_secret_card and location == line_location and tail == line_tail:
                    gate_id = line_split[0]
                    gate_info = gate_info_cache[gate_id]
                    response.append(
                        [gate_id, gate_info.gate_name, gate_info.gate_longitude, gate_info.gate_latitude,
                         line_timestamp])
            except:
                traceback.print_exc()

    print('response length is {}'.format(len(response)))
    return jsonify(response)


@app.route('/')
def index():
    return 'welcome to my webpage!'


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-p', '--port', default=8889, type=int, help='启动端口')
    parser.add_argument('-d', '--debug', default=False, type=bool, help='启动端口')
    args = parser.parse_args()

    port = args.port
    debug = args.debug
    app.run(port=port, host="0.0.0.0", debug=debug)